<route lang="json5">
{
  style: {
    navigationBarTitleText: '修改头像',
  },
}
</route>

<template>
  <view class="avatar-upload-page px-6 py-10">
    <!-- 裁剪组件 -->
    <wd-img-cropper
      v-model="showCropper"
      :img-src="cropSrc"
      @confirm="handleCropConfirm"
      @cancel="handleCropCancel"
    />

    <!-- 头像展示区 -->
    <view class="flex flex-col items-center">
      <image
        :src="finalAvatarUrl"
        mode="aspectFill"
        class="w-40 h-40 rounded-full border border-gray-300 shadow"
        @error="onAvatarError"
      />
      <text class="mt-4 text-gray-600 text-sm">建议使用清晰正方形图片</text>
    </view>

    <!-- 按钮区 -->
    <view class="mt-8 flex justify-center">
      <wd-button type="primary" size="large" @click="chooseAvatar">选择头像</wd-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { updateUserInfo } from '@/api/login'
import { useUserStore } from '@/store/user'

const store = useUserStore()
const defaultAvatar = '/static/person.png'
const avatarLoadFailed = ref(false)

const finalAvatarUrl = computed(() => {
  if (avatarLoadFailed.value) return defaultAvatar
  return store.userAvatar || defaultAvatar
})

const onAvatarError = () => {
  avatarLoadFailed.value = true
}

const headerObj = ref({
  Authorization: 'Bearer',
})

// 裁剪相关
const showCropper = ref(false)
const cropSrc = ref('')

const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      cropSrc.value = res.tempFilePaths[0]
      showCropper.value = true
    },
  })
}

const handleCropCancel = () => {
  showCropper.value = false
  cropSrc.value = ''
}

const handleCropConfirm = async ({ tempFilePath }) => {
  showCropper.value = false
  uni.uploadFile({
    url: import.meta.env.VITE_UPLOAD_BASEURL,
    filePath: tempFilePath, // 用本地路径
    name: 'file',
    header: headerObj.value,
    formData: {
      name: 'avatar_' + Date.now(),
    },
    success: async (uploadRes) => {
      const result = JSON.parse(uploadRes.data)
      if (result.code === 0) {
        const avatar = result.url
        await updateUserInfo({ avatar })
        store.setUserAvatar(avatar)
        avatarLoadFailed.value = false
        uni.showToast({ title: '上传成功', icon: 'success' })
        setTimeout(() => {
          uni.navigateBack()
        }, 1000)
      } else {
        uni.showToast({ title: result.msg || '上传失败', icon: 'none' })
      }
    },
    fail: () => {
      uni.showToast({ title: '上传失败', icon: 'none' })
    },
  })
}
</script>
<style scoped>
.avatar-upload-page {
  background-color: #fff;
  min-height: 100vh;
}
</style>
